import 'package:flutter/material.dart';
import 'package:p5/p5.dart';

class P5Page extends StatefulWidget {
  const P5Page({Key? key}) : super(key: key);

  @override
  _P5PageState createState() => _P5PageState();
}

class _P5PageState extends State<P5Page> with SingleTickerProviderStateMixin {
  late MySketch sketch;
  late PAnimator animator;

  @override
  void initState() {
    super.initState();
    sketch = new MySketch();
    // Need an animator to call the draw() method in the sketch continuously,
    // otherwise it will be called only when touch events are detected.
    animator = new PAnimator(this);
    animator.addListener(() {
      setState(() {
        sketch.redraw();
      });
    });
    animator.run();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('P5 Page')),
      body: Center(child: new PWidget(sketch)),
    );
  }
}

class MySketch extends PPainter {
  void setup() {
    size(300, 300);
    background(Colors.blue);
  }

  void draw() {
    fill(Colors.amber);
    rect(mouseX, mouseY, 50, 50);
  }
}
